// src/components/popups/sponsorOverview/companyContactsList/CompanyContactsModal.tsx

import type { FC } from 'react';
import { useState, useMemo } from 'react';
import SearchForm from '@/components/popups/sponsorOverview/companyContactsList/SearchForm';
import ResultTable from '@/components/popups/sponsorOverview/companyContactsList/ResultTable';
import Pagination from '@/components/sponsorDashboard/mainContent/Pagination';
import { fetchSponsorContactsByGroup, type CompanyContactsItem } from '@/services/sponsorDashboardService/sponsorContactsByGroup';
import type { CompanyContactsSearchParams } from '@/components/popups/sponsorOverview/companyContactsList/SearchForm';

interface CompanyContactsListModalProps {
  onClose: () => void;
}

type SortField = 'company_name' | 'first_name' | 'last_name' | 'position_title' | 'email' | 'phone' | 'mobile' | 'kc' | 'inv' | 'program_code' | 'faculty' | 'coop_program' | 'program_year' | 'status';
type SortDirection = 'asc' | 'desc';

const CompanyContactsListModal: FC<CompanyContactsListModalProps> = ({ onClose }) => {
  const [results, setResults] = useState<CompanyContactsItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [loadingProgress, setLoadingProgress] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [sortField, setSortField] = useState<SortField>('company_name');
  const [sortDirection, setSortDirection] = useState<SortDirection>('asc');
  const itemsPerPage = 10;

  const sortedResults = useMemo(() => {
    return [...results].sort((a, b) => {
      let aValue: string | number | undefined = a[sortField];
      let bValue: string | number | undefined = b[sortField];

      if (aValue === null || aValue === undefined) aValue = '';
      if (bValue === null || bValue === undefined) bValue = '';

      if (sortField === 'program_year' || sortField === 'kc' || sortField === 'inv') {
        aValue = Number(aValue) || 0;
        bValue = Number(bValue) || 0;
      } else {
        aValue = String(aValue).toLowerCase();
        bValue = String(bValue).toLowerCase();
      }

      if (aValue < bValue) {
        return sortDirection === 'asc' ? -1 : 1;
      }
      if (aValue > bValue) {
        return sortDirection === 'asc' ? 1 : -1;
      }
      return 0;
    });
  }, [results, sortField, sortDirection]);

  const handleSortChange = (field: SortField, direction: SortDirection) => {
    setSortField(field);
    setSortDirection(direction);
    setCurrentPage(1);
  };

  const handleSearch = async (params: CompanyContactsSearchParams) => {
    setLoading(true);
    setResults([]);
    setCurrentPage(1);
    setLoadingProgress('');

    try {
      const allResults: CompanyContactsItem[] = [];
      let currentPage = 1;
      let hasMoreData = true;
      const pageSize = 100;

      // Fetch all data by making multiple API calls
      while (hasMoreData) {
        setLoadingProgress(`Fetching ...`);

        const queryParams = {
          year_from: params.startYear ?? 20,
          year_to: params.endYear ?? 2099,
          current: params.status?.toLowerCase() === 'current'
            ? true
            : params.status?.toLowerCase() === 'not current'
              ? false
              : undefined,
          program_code: params.programType === 'PROGRAM' ? params.programCode : undefined,
          faculty: params.programType === 'SCHOOL' ? params.school : undefined,
          coop_program: params.programType === 'CO-OP PROGRAM' ? params.coopProgram : undefined,
          page: currentPage,
          page_size: pageSize,
        };

        const response = await fetchSponsorContactsByGroup(queryParams);

        allResults.push(...response.items);

        // Check if there are more pages using the actual page_size
        const totalPages = Math.ceil(response.meta.total / pageSize);
        if (currentPage >= totalPages) {
          hasMoreData = false;
        } else {
          currentPage++;
        }
      }

      setTimeout(() => {
        setResults(allResults);
        setLoading(false);
        setLoadingProgress('');
      }, 300);
    } catch (err) {
      console.error('Error fetching sponsor contacts by group:', err);
      setResults([]);
      setLoading(false);
      setLoadingProgress('');
    }
  };

  const paginatedResults = sortedResults.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 dark:bg-black/80 backdrop-blur-sm p-2 sm:p-4 font-poppins text-xs sm:text-sm md:text-base"
      onClick={onClose}
    >
      <div
        className="w-full max-w-6xl bg-white dark:bg-slate-900 rounded-2xl shadow-2xl dark:shadow-blue-900 overflow-hidden animate-fade-in-up max-h-[90vh] overflow-y-auto relative border border-gray-200 dark:border-slate-800"
        onClick={e => e.stopPropagation()}
      >
        {/* Header */}
        <div className="px-4 sm:px-6 py-4 sm:py-5 bg-white dark:bg-slate-900 text-gray-800 dark:text-cyan-200 flex justify-between items-center border-b border-gray-200 dark:border-slate-800 rounded-t-2xl shadow-sm text-xs sm:text-sm md:text-base">
          <h2 className="text-base sm:text-lg md:text-2xl font-extrabold tracking-tight break-words text-blue-700 dark:text-cyan-300">
            Company & Contact List
          </h2>
          <button
            onClick={onClose}
            className="w-9 h-9 flex items-center justify-center rounded-full text-xl font-bold text-gray-500 dark:text-gray-300 hover:text-red-600 dark:hover:text-red-300 hover:bg-red-50 dark:hover:bg-red-900 transition focus:outline-none focus:ring-2 focus:ring-red-300 dark:focus:ring-red-800"
          >
            ×
          </button>
        </div>

        {/* Body */}
        <div className="p-3 sm:p-6 space-y-4 text-xs sm:text-sm md:text-base text-gray-800 dark:text-gray-100 bg-white dark:bg-slate-900">
          <SearchForm onSearch={handleSearch} />

          {loading ? (
            <div className="text-center text-gray-400 dark:text-gray-500 animate-pulse py-8 text-base sm:text-lg">
              {loadingProgress || 'Loading results...'}
            </div>
          ) : (
            <ResultTable
              data={paginatedResults}
              sortField={sortField}
              sortDirection={sortDirection}
              onSortChange={handleSortChange}
            />
          )}

          {sortedResults.length > itemsPerPage && (
            <Pagination
              currentPage={currentPage}
              setCurrentPage={setCurrentPage}
              totalCount={sortedResults.length}
              pageSize={itemsPerPage}
            />
          )}
        </div>
      </div>
    </div>
  );
};

export default CompanyContactsListModal;